import { createRouter, createWebHashHistory } from "vue-router";
import { staticRouter } from "@/routers/modules/staticRouters";
import NProgress from "@/config/nprogress";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";


const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRouter,
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const authStore = useAuthStore();
  NProgress.start();
  if (to.path.toLocaleLowerCase() === '/login') {
    if (userStore.token) return next(from.fullPath);
    return next();
  }
  if (!userStore.token) return next({ path: '/login', replace: true });
  if (!authStore.authMenuListGet.length) {
    await initDynamicRouter();

    return next({ ...to, replace: true });
  }
  next()

})

router.afterEach(() => {
  NProgress.done();

});

export default router